import { defineStore } from 'pinia';
import { reqLogin } from '@/api/user';
import { UserState } from './types/type';
import { loginFormData, loginResponseData } from '@/api/user/type';
import { GET_TOKEN, SET_TOKEN } from '@/utils/tokens';
import { constantRoute } from '@/router/routes';

const useUserStore = defineStore('User', {
  // 小仓库存储数据的地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
    };
  },
  // 异步处理
  actions: {
    async userLogin(data: loginFormData) {
      const result: loginResponseData = await reqLogin(data);
      const message = result.data;
      if (result.code === 200) {
        this.token = message;
        SET_TOKEN(message);
        return 'ok';
      } else {
        return Promise.reject(new Error(message));
      }
    },
  },
});

export default useUserStore;
